package cn.zs.supply.common.utils;
/*
 * huirong Inc.
 * Copyright (c) 2016 All Rights Reserved.
 * Author     :liyb
 * Create Date:2016年5月5日
 */


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.util.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 图片Base64工具类
 */
public class Base64Util {
    private static  final Log log = LogFactory.getLog(Base64Util.class);
    
    private static String FILE_PATH ="D:\\kry\\data\\";
    //private static String FILE_PATH=ConfigProperties.getProperty("ocr_file_path");
   
    public static void main(String[] args) {
        File file = new File("F:\\材料图片\\6588.jpg");
        String imageBase64Str = getImageStrFromFile(file);
        System.out.println(imageBase64Str);
//        File tmpfile = generateImage(imageBase64Str);
//        System.err.println(tmpfile);
//    	System.out.println(decoderStr("W3sidXNlck5hbWUiOiLmnY7lsqnlhpsiLCJvcmRlck5vIjoiamNyejIwMTcwMTI0MTQ0ODMyMzUiLCJyZXBvcnRJZCI6IjIwMTcwMTI0NFlEQjVGMDQifV0"));
    }
    
    public static String getImageStrFromFile(File file) {  
        InputStream in = null;  
        byte[] data = null;  
        // 读取图片字节数组  
        try {  
            in = new FileInputStream(file);  
            data = new byte[in.available()];  
            in.read(data);  
            in.close();  
        } catch (IOException e) {  
        	 log.error("base64Util getImageStrFromFile>>>>>exception msg"+e.getMessage());
        }  
        // 返回Base64编码过的字节数组字符串  
        return Base64.encodeBase64String(data);  
    }
   
    /** 
     * 将Base64位编码的图片进行解码，并保存到指定目录 
     *  
     * @param base64 
     *            base64编码的图片信息 
     * @return 
     */  
    public static File decodeBase64ToImage(String imageBase64Str) {  
    	
      if(StringUtils.isBlank(imageBase64Str)){
    	  return null;
      }
      File file =null;	
      FileOutputStream out=null;
      try {  
    	  //生成jpeg图片
        String imgFilePath = ConfigProperties.getProperty("fs.storage.nas.roo")+FileUtil.getTargetPath()+String.valueOf(System.currentTimeMillis())+ new Random().nextInt()+".jpg";
        out = new FileOutputStream(new File(imgFilePath));  
        byte[] decoderBytes = Base64.decodeBase64(imageBase64Str);  
        out.write(decoderBytes);  
        out.close();  
        file = new File(imgFilePath);
        return file;
      }catch (Exception e) {
    	  log.error("base64Util decodeBase64ToImage>>>>>exception msg"+e.getMessage());
      } finally {
          if(out!=null){
              try {
                  out.close();
              } catch (IOException e) {}
          }
      }
      return  file;
    } 
    
    
    /**
     * base64字符串转换成byte数组
     * @param base64String
     * @return
     */
	public static byte[] base64StringToByte(String jsonRiskControl) {
		if (jsonRiskControl == null) 
            return null;
        //替换字符
		jsonRiskControl = jsonRiskControl.replaceAll("\\*", "+").replaceAll("-", "/");
        //Base64解码
        byte[] b = null;
        b=Base64.decodeBase64(jsonRiskControl);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {//调整异常数据
                b[i] += 256;
            }
        }
        return b;
	}
	
	 /**
     * base64 把字符串转码为base64字符串
     * @Title: encoderStr
     * @param: @param param
     * @param: @return   
     * @return: String   
     * @throws
     */
    public static String encoderStr(String param){
    	String encoderStr = "";
    	try{
    		if(StringUtil.isNotBlank(param)){
    			BASE64Encoder encoder = new BASE64Encoder();
        		encoderStr = encoder.encode(param.getBytes());
    		}else{
    			return encoderStr;
    		}
    	}catch(Exception e){
    		encoderStr = "";
    		e.printStackTrace();
    	}
    	return encoderStr;
    }
    
    /**
     * 把base64字符串解码为字符串
     * @Title: decoderStr
     * @param: @param param
     * @param: @return   
     * @return: String   
     * @throws
     */
    public static String decoderStr(String param){
    	String decoderStr = "";
    	try{
    		if(StringUtil.isNotBlank(param)){
    			BASE64Decoder decoder = new BASE64Decoder();
        		byte[] b = decoder.decodeBuffer(param);
        		decoderStr = new String(b);
    		}else{
    			return decoderStr;
    		}
    	}catch(Exception e){
    		decoderStr = "";
    		e.printStackTrace();
    	}
    	return decoderStr;
    }
 
    /**
     * 功能：图片转化成base64字符串
     *
     * @author yh1.yu
     * @since 2015-8-9
     * @return
     * @throws Exception 
     */
    public static String getBase64Image(String imgFile) throws Exception {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = getByteData(imgFile);
        BASE64Encoder ecoder = new BASE64Encoder();
        String base64ImageEncodeStr = ecoder.encode(data);
        return base64ImageEncodeStr;
    }
    public static String getBase64ImageFile(InputStream imgFileInput) throws Exception {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = readInputStream(imgFileInput);
        BASE64Encoder ecoder = new BASE64Encoder();
        String base64ImageEncodeStr = ecoder.encode(data);
        return base64ImageEncodeStr;
    }
    public static byte[] getByteData(String imgFile) {
        byte[] data = null;
        try {
            //读取图片字节数组
            URL url = new URL(imgFile);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据 
            data = readInputStream(inStream);//得到图片的二进制数据
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static InputStream getInputData(String imgFile) {
    	InputStream inStream = null;
        try {
            //读取图片字节数组
            URL url = new URL(imgFile);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            inStream = conn.getInputStream();//通过输入流获取图片数据 
           
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inStream;
    }
    public static byte[] readInputStream(InputStream instream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1204];
        int len = 0;
        while ((len = instream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        instream.close();
        return outStream.toByteArray();
    }
    
    /**
     * byte数字转换成base64字符串
     * @param b
     * @return
     */
    public static String byteToStringBase64(byte[] b){
        String base64Data="";
        try {
           
            base64Data = Base64.encodeBase64String(b);
            if(StringUtils.isNotEmpty(base64Data)){
                base64Data = base64Data.replaceAll("\\+", "*").replaceAll("\\/", "-");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64Data;//返回Base64编码过的字节数组字符串
    }
    
  
}
